package com.teligen.zkdb.db;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import java.sql.Connection;
import java.util.Properties;

public class DruidUtil {

    private static Connection connection;

    private static synchronized Connection createDruid(DbConfig dbConfig) throws Exception{
        Properties properties = new Properties();
        properties.setProperty("url",dbConfig.getUrl());
        properties.setProperty("username",dbConfig.getUsername());
        properties.setProperty("password",dbConfig.getPassword());
        properties.setProperty("driverClassName",dbConfig.getDriverClassName());
        Connection connection = DruidDataSourceFactory.createDataSource(properties).getConnection();
        return connection;
    }

    public static Connection createNewConnect(DbConfig dbConfig) {
        try {
            if (dbConfig == null){
                return null;
            }
            connection = createDruid(dbConfig);
            System.out.println("创建新连接==>" + dbConfig);
            return connection;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }


    public static Connection switchConnect(DbConfig dbConfig) {
        try {
            if (connection != null){
                connection.close();
            }
            connection = createDruid(dbConfig);
            System.out.println("切换连接==>" + dbConfig);
            return connection;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
